/*
 * FastAvg.h
 *
 *  Created on: Sept 28, 2021
 *      Author: Vincent Manoukian + Yannick Richter
 */

#include "FastAvg.h"
#include "string.h"

void FA_Init(fast_avg_t* fa , size_t size)
{
	if(size > AVG_MAXLEN)
	{
		return;
	}
	if(fa == NULL)
	{
		return;
	}
	fa->avgSize = size;
	fa->currentIndex = 0;
	fa->sumOfSamples = 0;
	memset(fa->samples,0,size*sizeof(uint32_t));
}

void FA_AddValue(fast_avg_t* fa , uint32_t value)
{
	if(fa == NULL)
	{
		return;
	}
	
	// remove the previous value
	fa->sumOfSamples -= fa->samples[fa->currentIndex];
	
	// Add the new value
	fa->samples[fa->currentIndex] = value;
	fa->sumOfSamples += value;

	// prepare the next add
	fa->currentIndex = (fa->currentIndex + 1) % (fa->avgSize);
}

uint32_t FA_GetAvg(fast_avg_t* fa)
{
	return fa->sumOfSamples/fa->avgSize;
}

uint32_t FA_Process(fast_avg_t* fa,uint32_t value)
{
	FA_AddValue(fa,value);
	return fa->sumOfSamples / fa->avgSize;
}

void FA_Clear(fast_avg_t* fa)
{
	memset(fa->samples,0,fa->avgSize*sizeof(uint32_t));
	fa->sumOfSamples = 0;
}


void FAf_Init(fast_avgf_t* fa , size_t size)
{
	if(size > AVG_MAXLEN)
	{
		return;
	}
	if(fa == NULL)
	{
		return;
	}
	fa->avgSize = size;
	fa->currentIndex = 0;
	fa->sumOfSamples = 0.0;
	memset(fa->samples,0,size*sizeof(float));
}

void FAf_AddValue(fast_avgf_t* fa , float value)
{
	if(fa == NULL)
	{
		return;
	}
	
	// remove the previous value
	fa->sumOfSamples -= fa->samples[fa->currentIndex];
	
	// Add the new value
	fa->samples[fa->currentIndex] = value;
	fa->sumOfSamples += value;

	// prepare the next add
	fa->currentIndex = (fa->currentIndex + 1) % (fa->avgSize);
}

float FAf_GetAvg(fast_avgf_t* fa)
{
	return fa->sumOfSamples/fa->avgSize;
}

float FAf_Process(fast_avgf_t* fa,float value)
{
	FAf_AddValue(fa,value);
	return fa->sumOfSamples / fa->avgSize;
}

void FAf_Clear(fast_avgf_t* fa)
{
	memset(fa->samples,0,fa->avgSize*sizeof(uint32_t));
	fa->sumOfSamples = 0;
}



